// clients.js
import {http} from '../../js/http.js';

export const Clients = {
    timer: null,
    mount() {
        console.log("【客户端】组件挂载");
        this.fetchClients();
        this.timer = setInterval(() => {
            this.fetchClients();
        }, 5000);
    },
    fetchClients() {
        http.get('/api/clients').then(data => {
            this.renderTable(data);
        })
    },
    renderTable(clients) {
        const tbody = document.getElementById('clients-table-body');
        if (!clients || !clients.length) {
            tbody.innerHTML = '<tr><td colspan="5" style="text-align:center;">暂无客户端</td></tr>';
            return;
        }

        const rows = clients.map(client => `
            <tr>
                <td>${client.clientId}</td>
                <td>
                    <span class="status ${client.connected ? 'online' : 'offline'}">
                        ${client.connected ? '在线' : '离线'}
                    </span>
                </td>
                <td>${client.connectTime ? new Date(client.connectTime).toLocaleString() : '--'}</td>
                <td>${client.ip}:${client.port}</td>
                <td>
                    <button class="action-btn disconnect" onclick="disconnectClient('${client.id}')">断开连接</button>
                </td>
            </tr>
        `).join('');

        tbody.innerHTML = rows;
    },
    unmount() {
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
            console.log("【客户端】组件已卸载");
        }
    }
};
